<template>
    <div>
        <el-card shadow="always" :body-style="{ padding: '20px' }">
            <el-form inline>
                <el-form-item>
                    <el-input v-model="username" placeholder="用户名" />
                </el-form-item>

                <el-button type="primary" icon="el-icon-search" @click="getUserList()">查询</el-button>
                <el-button type="default" @click="clear">清空</el-button>
            </el-form>
            <div style="margin-bottom: 20px">
                <el-button type="primary" @click="addUser">添 加</el-button>
                <el-button type="danger" @click="removeAllChecked" :disabled="!selectionIds.length">批量删除</el-button>
            </div>

            <el-table :data="userList" border stripe v-loading="loading" @selection-change="checkedChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column type="index" label="序号" width="80" align="center" />

                <el-table-column prop="username" label="用户名" width="150" />
                <el-table-column prop="nickName" label="用户昵称" />
                <el-table-column prop="roleName" label="角色列表" />

                <el-table-column prop="gmtCreate" label="创建时间" width="180" />
                <el-table-column prop="gmtModified" label="更新时间" width="180" />
                <el-table-column label="操作" width="240">
                    <template slot-scope="{row}">
                        <el-button type="info" size="small" icon="el-icon-user-solid" @click="showAssignRole(row)">
                        </el-button>
                        <el-button type="primary" size="small" icon="el-icon-edit-outline" @click="toEdit(row)">
                        </el-button>
                        <el-popconfirm :title="`您确定删除${row.username}吗？`" @confirm="remove(row)" style="margin-left: 10px;">
                            <el-button slot="reference" type="danger" size="small" icon="el-icon-delete-solid">
                            </el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>

            </el-table>


            <el-pagination @size-change="handleSizeChange" @current-change="getUserList" :current-page="page"
                :total="total" :page-size="limit" :page-sizes="[5, 10, 20, 30, 40, 50, 100]" style="padding: 20px 0;"
                layout="prev, pager, next, jumper, ->, sizes, total" />


            <!-- 点击添加弹出的对话框 -->
            <el-dialog :title="user.id ? '修改用户' : '添加用户'" :visible.sync="dialogFormVisible">
                <el-form :model="user" :rules="rules" ref="userRef" label-width="80px" width="80%">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="user.username" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="用户昵称" prop="nickName">
                        <el-input v-model="user.nickName" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item v-if="!user.id" label="用户密码" prop="password">
                        <el-input v-model="user.password" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveUser">确 定</el-button>
                </div>
            </el-dialog>


            <!-- 设置角色的对话框 -->
            <el-dialog title="设置角色" :visible.sync="dialogFormVisible1">
                <el-form label-width="80px" width="80%">
                    <el-form-item label="用户名">
                        <el-input :placeholder="name" :disabled="true" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="角色列表">
                        <template>
                            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
                                @change="handleCheckAllChange">全选</el-checkbox>
                            <div style="margin: 15px 0;"></div>
                            <el-checkbox-group v-model="userRoleIds" @change="handleCheckedCitiesChange">
                                <el-checkbox v-for="(role, index) in allRolesList" :label="role.id" :key="role.id">
                                    {{ role.roleName }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </template>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="saveRole">保 存</el-button>
                    <el-button @click="dialogFormVisible1 = false">取 消</el-button>
                </div>
            </el-dialog>
        </el-card>

    </div>
</template>

<script>
import { reqGetUserList, reqAddOrUpdateUser, reqRemoveUser, reqBatchRemove, reqToAssign, reqDoAssign } from '@/api/acl/users';


export default {
    data() {
        return {
            page: 1,
            limit: 5,
            username: '',
            userList: [], //分页列表
            total: 1, //列表总条数
            loading: false, //加载效果
            dialogFormVisible: false,
            user: {}, //每个用户
            selectionIds: [],//选中的管理用户id的数组
            checkAll: false, // 全选全不选
            isIndeterminate: true,
            dialogFormVisible1: false,
            allRolesList: [], //全部角色列表
            userRoleIds: [], //用户角色列表的id
            name: '',//用户名
            userId: '',
            rules: {
                username: [
                    { required: true, message: '请输入用户名' },
                    { min: 4, message: '用户名不能小于4位' }
                ],
                password: [
                    { required: true, validator: this.validatePassword }
                ],
            }
        }
    },
    mounted() {
        this.getUserList()
    },
    methods: {
        //自定义密码校验
        validatePassword(rule, value, callback) {
            if (!value) {
                callback('请输入密码')
            } else if (!value || value.length < 6) {
                callback('密码不能小于6位')
            } else {
                callback()
            }
        },
        // 获取用户信息
        async getUserList(page = 1) {
            // 开启加载效果
            this.loading = true
            //更新页码
            this.page = page
            // 发请求
            let result = await reqGetUserList(this.page, this.limit, this.username)
            // console.log(result);
            let { items, total } = result.data
            // 存储数据
            this.userList = items
            this.total = total
            // 关闭加载效果
            this.loading = false
        },
        // 设置一页显示几条
        handleSizeChange(limit) {
            this.limit = limit
            this.getUserList()
        },
        // 清空输入框
        clear() {
            this.username = ''
        },
        // 点击添加按钮
        addUser() {
            // 清空数据
            this.user = {}
            this.dialogFormVisible = true
            // 清空表单验证
            this.$refs.userRef.resetFields()
        },
        // 点击确定按钮
        async saveUser() {
            this.$refs.userRef.validate(async (valid) => {
                if (valid) {
                    try {
                        await reqAddOrUpdateUser(this.user)
                        this.$message({
                            message: this.user.id ? '修改用户成功' : '添加用户成功',
                            type: 'success',
                            center: true
                        });
                        this.dialogFormVisible = false
                        this.getUserList()
                    } catch (error) {

                    }
                }
            })
        },
        // 点击修改按钮
        toEdit(row) {
            this.user = row
            this.dialogFormVisible = true
            // 清空表单验证
            this.$refs.userRef.resetFields()
        },
        // 点击删除按钮删除某个管理用户
        async remove(row) {
            try {
                await reqRemoveUser(row.id)
                this.$message({
                    message: `删除${row.username}成功`,
                    type: 'success',
                    center: true
                });
                this.getUserList(this.page)
            } catch (error) {

            }
        },
        // 选中的管理用户
        checkedChange(selection) {
            // console.log(selection);
            // this.selectionIds = selection.map(item => item.id)
            this.selectionIds = selection
        },
        // 批量删除
        async removeAllChecked() {
            // console.log(this.selectionIds);
            // try {
            //     await reqBatchRemove(this.selectionIds)
            //     this.$message({
            //         message: '批量删除成功',
            //         type: 'success',
            //         center: true
            //     });
            // } catch (error) {

            // }
            this.selectionIds.forEach(item => {
                this.remove(item)
            })
        },
        // 点击设置角色按钮
        async showAssignRole(row) {
            console.log(row);
            this.dialogFormVisible1 = true
            this.name = row.username
            this.userId = row.id
            let result = await reqToAssign(row.id)
            console.log(result);
            let { assignRoles, allRolesList } = result.data
            // 用户所有角色的id
            this.userRoleIds = assignRoles.map(item => item.id)
            // 所有的角色列表
            this.allRolesList = allRolesList
            // 当用户的角色 === 所有角色时 -> 全选
            this.checkAll = allRolesList.length === assignRoles.length

            this.isIndeterminate = assignRoles.length > 0 && assignRoles.length < allRolesList.length
        },

        handleCheckAllChange(val) {
            console.log(val);
            this.userRoleIds = val ? this.allRolesList.map(item => item.id) : [];
            this.isIndeterminate = false;
        },
        handleCheckedCitiesChange(value) {
            console.log(value);
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.allRolesList.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.allRolesList.length;
        },
        // 点击保存按钮给用户分配角色
        async saveRole() {
            try {
                let { userId, userRoleIds } = this
                let roleId = userRoleIds.join(',')
                await reqDoAssign(userId, roleId)
                this.$message.success('用户分配角色成功')
                this.dialogFormVisible1 = false
                this.getUserList()
            } catch (error) {

            }
        }
    },

}
</script>

<style scoped>

</style>